import { ref } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { permission, plugin } from '@/api/manage'

// 初始化
const indexStore = store()

// 是否执行初始化
indexStore.init = false
indexStore.initLoad = false
indexStore.initCall = []

// 权限和插件
indexStore.permission = ref([])
indexStore.plugin = ref([])

// 加载
indexStore.get = async(func) => {
  indexStore.initCall.push(func)
  // 当前正在加载
  if(indexStore.initLoad) return 
  // 还未初始化
  if(!indexStore.init) {
    indexStore.initLoad = true
    await indexStore.getPermission()
    await indexStore.getPlugin()
    indexStore.init = true
    indexStore.initLoad = false
  }
  // 执行所有回调
  while(indexStore.initCall.length > 0) {
    indexStore.initCall.shift()()
  }
}

// 权限
indexStore.getPermission = () => {
  return new Promise((resolve, jeject) => {
    permission().then(res => {
      resolve(res)
      indexStore.permission.value = res
      app.permission.build(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 插件
indexStore.getPlugin = () => {
  return new Promise((resolve, jeject) => {
    plugin().then(res => {
      resolve(res)
      indexStore.plugin.value = res
      app.plugin.build(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default indexStore